package cn.ronghuanet.base.service.impl;

import cn.ronghuanet.base.service.IVerifyCodeService;
import cn.ronghuanet.base.util.AjaxResult;
import cn.ronghuanet.base.util.StrUtils;
import cn.ronghuanet.base.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult getImageCode(String key) {
        AjaxResult ajaxResult = AjaxResult.me();
        try {
            //1 生成4位数验证码
            String imageCode = StrUtils.getComplexRandomString(4);
            //2 生成的验证码转换为base64格式
            String base64Code = VerifyCodeUtils.VerifyCode(120, 30, imageCode);
            //3 将生成的验证码放入redis中
            redisTemplate.opsForValue().set(key,imageCode,5, TimeUnit.MINUTES);
            ajaxResult.setResultObj(base64Code);
        } catch (IOException e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false).setMessage("服务器错误");
        }
        return ajaxResult;
    }
}
